package com.cssl.repository;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.cssl.util.InfoCode;
import com.cssl.util.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常捕获 (saToken)
 */
@RestControllerAdvice
public class GlobalException {
    //未登录异常
    @ExceptionHandler(NotLoginException.class)
    public Result handlerException(NotLoginException e) {
        // 打印堆栈，以供调试
        e.printStackTrace();
        // 返回给前端
        return Result.fail(InfoCode.UNLOGIN,e.getMessage(),System.currentTimeMillis());
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    public Result handlerException(NotRoleException e) {
        e.printStackTrace();
        return Result.fail(InfoCode.UNAUTHORIZED,"缺少角色：" + e.getRole(),System.currentTimeMillis());
    }

    // 拦截：服务封禁异常
    @ExceptionHandler(DisableServiceException.class)
    public Result handlerException(DisableServiceException e) {
        e.printStackTrace();
        return  Result.fail(InfoCode.FAILED,"当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封",System.currentTimeMillis());
    }

    // 拦截：其它所有异常
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {
        System.out.println("被捕获 = ");
        e.printStackTrace();
        return  Result.fail(InfoCode.FAILED,e.getMessage(),System.currentTimeMillis());
    }
}
